package com.lagou.job.config;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.lagou.job.common.Constant;
import com.lagou.job.service.PositionService;
import com.lagou.job.util.GuaveCacheUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PostConstruct;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * GuavaCache配置类
 * @author yzh
 */
@Configuration
public class GuaveCacheConfig {

    @Autowired
    private PositionService positionService;

    private LoadingCache<String, Object> cache;

    {
        //创建GuavaCache
        cache = CacheBuilder.newBuilder()
                //最大容量
                .maximumSize(9)
                //开启统计功能
                .recordStats()
                //设置过期时间 ： 5秒未更新则失效
                .expireAfterWrite(5, TimeUnit.SECONDS)
                .build(new CacheLoader<String, Object>() {
                    @Override
                    public Object load(String s) throws Exception {
                        //如果本地缓存中没有进行回源
                        return positionService.getHotPositionFromBySource();
                    }
                });
    }

    /**
     * 初始化本地缓存
     */
    @PostConstruct
    private void init() throws ExecutionException {
        //获取热门职位ID列表
        cache.get(Constant.POSITION_HOT_LIST_CACHE_KEY);
        System.out.println("初始化GuaveCache成功");
        GuaveCacheUtil.forEachCache(cache);
    }

    @Bean
    public LoadingCache<String, Object> guavaCache() {
        return cache;
    }
}
